package org.aceor.mddal.atom;

import org.aceor.mddal.atom.adapter.AbstractAtomPreparedStatementAdapter;
import org.aceor.mddal.common.monitor.Monitor;
import org.aceor.mddal.common.monitor.MonitorPoint;
import org.aceor.mddal.common.sqlparser.util.SQLCommonUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * Created by lxue on 16/3/27.
 */
public class AtomPreparedStatementWrapper extends AbstractAtomPreparedStatementAdapter implements PreparedStatement {
    protected String sql;

    public AtomPreparedStatementWrapper(PreparedStatement preparedStatement, Connection atomConnectionWrapper, String sql) {
        super(preparedStatement, atomConnectionWrapper);
        this.sql = sql;
    }


    @Override
    public ResultSet executeQuery() throws SQLException {
        checkClosed();
        AtomDataSourceWrapper atomDataSourceWrapper = ((AtomConnectionWrapper)connection).getAtomDsWrapper();
        Monitor.startSqlExecuteMonitor(sql, atomDataSourceWrapper.getGroupDsId(), atomDataSourceWrapper.getAtomDsId());
        try {
            return ((PreparedStatement)targetStatement).executeQuery();
        } finally {
            Monitor.stop(MonitorPoint.EXECUTE_SQL);
        }
    }

    @Override
    public int executeUpdate() throws SQLException {
        checkClosed();
        AtomDataSourceWrapper atomDataSourceWrapper = ((AtomConnectionWrapper)connection).getAtomDsWrapper();
        Monitor.startSqlExecuteMonitor(sql, atomDataSourceWrapper.getGroupDsId(), atomDataSourceWrapper.getAtomDsId());
        try {
            return ((PreparedStatement)targetStatement).executeUpdate();
        } finally {
            Monitor.stop(MonitorPoint.EXECUTE_SQL);
        }
    }

    @Override
    public boolean execute() throws SQLException {
        if (SQLCommonUtil.isQuerySql(sql)) {
            executeQuery();
            return true;
        } else {
            executeUpdate();
            return false;
        }
    }
}
